/** * 基础菜单 商品管理 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">生产信息</el-breadcrumb-item>
      <el-breadcrumb-item>仓库定义</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->

    <el-form
      :inline="true"
      :model="formInline"
      class="user-search"
      align="left"
    >
      <el-form-item>
        <el-button type="primary" @click="addOne()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-upload
          class="upload-demo"
          action="/api/warehouse/import"
          :headers="headers"
          :on-success="handlesuccess"
          :before-upload="beforeUpload"
        >
          <el-button type="success">导入</el-button>
        </el-upload>
      </el-form-item>
      <el-button type="danger" @click="exportData()">导出</el-button>
      <el-button
        type="warning"
        :disabled="batchDeleteArr.length === 0"
        @click="deleteSome(batchDeleteArr)"
        >批量删除</el-button
      >
      <el-form-item label="搜索：">
        <el-input
          size="small"
          v-model="formInline.warehousename"
          placeholder="输入仓库名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search()"
          >搜索</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="danger"
          @click="reset()"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      border
      element-loading-text="拼命加载中"
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column
        sortable
        prop="warehouse_id"
        label="仓库编码"
        width="200"
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="warehousename"
        label="仓库名称"
        width="200"
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="warehouse_classify"
        label="仓库分类"
        width="200"
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="warehouse_style"
        label="仓库类型"
        width="200"
      >
      </el-table-column>
      <el-table-column
        sortable
        prop="warehouse_remark"
        label="备注"
        width="200"
      >
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="update(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteOne(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
      align="center"
    ></Pagination>
    <!-- 新增页面 -->
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      :before-close="closeDialog"
    >
      <el-form
        label-position="left"
        label-width="100px"
        :model="editForm"
        :rules="rules"
        ref="editForm"
      >
        <el-form-item label="仓库编码" prop="warehouse_id">
          <el-input
            size="small"
            v-model="editForm.warehouse_id"
            auto-complete="off"
            placeholder="示例:CPCK01"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehousename">
          <el-input
            size="small"
            v-model="editForm.warehousename"
            auto-complete="off"
            placeholder="示例：手机库"
          ></el-input>
        </el-form-item>
        <el-form-item label="仓库类型" prop="warehouse_style">
          <el-select
            size="small"
            v-model="editForm.warehouse_style"
            auto-complete="off"
            placeholder="请选择仓库分类"
            ><el-option
              v-for="item in warehouseData"
              :key="item.id"
              :value="item.type_name"
              :label="item.type_name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库分类" prop="warehouse_classify">
          <el-input
            size="small"
            v-model="editForm.warehouse_classify"
            auto-complete="off"
            placeholder="请输入仓库分类"
            @focus="addStyle()"
          >
          </el-input>
          <el-dialog
            title="仓库分类"
            :visible.sync="LogDialogVisible"
            append-to-body
          >
            <addstyle
              @sendClassify="getClassify"
              @cancelClassify="cancelClassify"
            ></addstyle
          ></el-dialog>
        </el-form-item>

        <el-form-item label="备注" prop="warehouse_remark">
          <el-input
            type="textarea"
            size="small"
            v-model="editForm.warehouse_remark"
            auto-complete="off"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" @click="cancelDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="save()"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import addstyle from "@/components/AddWarehouseStyle.vue";
import axios from "axios";
import { deptList, deptSave, deptDelete } from "../../api/userMG";
import Pagination from "../../components/Pagination";
export default {
  data() {
    //校验器
    var checkCode = (rule, value, callback) => {
      this.$axios.get("/api/warehouse/findByCode/" + value).then(Response => {
        if (Response.data.code == 500) {
          callback();
        }
        callback(new Error("编码已存在！"));
      });
    };
    var checkName = (rule, value, callback) => {
      this.$axios
        .get("/api/warehouse/findByWname/" + encodeURI(encodeURI(value)))
        .then(Response => {
          if (Response.data.code == 500) {
            callback();
          }
          callback(new Error("名称已存在！"));
        });
    };
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      LogDialogVisible: false,
      title: "添加",
      batchDeleteArr: [],
      warehouseData: [],
      editForm: {
        id: "",
        warehousename: "",
        warehouse_id: "",
        warehouse_classify: "",
        warehouse_style: "",
        warehouse_remark: "",
        token: localStorage.getItem("logintoken")
      },
      // rules表单验证
      rules: {
        warehousename: [
          { required: true, message: "请输入仓库名称", trigger: "blur" },
          { min: 1, max: 20, message: "请输入1~20个字符", trigger: "blur" },
          { validator: checkName, trigger: "blur" }
        ],
        warehouse_id: [
          { required: true, message: "请输入仓库编码", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]{6}$/,
            message: "请输入6位数字、字母",
            trigger: "blur"
          },
          { validator: checkCode, trigger: "blur" }
        ],
        warehouse_classify: [
          { required: true, message: "请输入仓库分类", trigger: "change" }
        ],
        warehouse_style: [
          { required: true, message: "请输入仓库类型", trigger: "change" }
        ]
      },
      formInline: {
        page: 1,
        limit: 10,
        varLable: "",
        varName: "",
        warehousename: "",
        warehouse_id: "",
        warehouse_remark: "",
        token: localStorage.getItem("logintoken")
      },
      // 删除部门
      seletedata: {
        ids: "",
        token: localStorage.getItem("logintoken")
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      }
    };
  },
  // 注册组件
  components: {
    Pagination,
    addstyle
  },
  //

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline);
  },
  // 获取token
  computed: {
    headers() {
      return {
        Authorization: localStorage.getItem("logintoken")
      };
    }
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 初始化表单数据
    getdata(parameter) {
      // 模拟数据开始
      this.$axios
        .get(
          "/api/warehouse/findAll/" +
            this.pageparm.currentPage +
            "/" +
            this.pageparm.pageSize
        )
        .then(res => {
          console.log(res.data.data);
          if (res.data.code == 200) {
            this.listData = res.data.data.list;
            this.pageparm.total = res.data.data.total;
          }
        })
        .catch(() => {});
    },

    changeSize(val) {
      this.pageparm.pageSize = val;
      this.pageparm.currentPage = 1;
      // 重新调用获取数据方法
      this.getdata(this.formInline);
    },
    changeCurrent(val) {
      this.pageparm.currentPage = val;
      // 重新调用获取数据方法
      this.getdata(this.formInline);
    },

    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getdata(this.formInline);
    },
    //获取分类子组件传值
    getClassify(data) {
      console.log(this.editForm.warehouse_classify + "000");
      this.editForm.warehouse_classify = data;
      this.LogDialogVisible = false;
      console.log(this.editForm.warehouse_classify + "111");
    },

    cancelClassify(data) {
      this.editForm.warehouse_classify = data;
      this.LogDialogVisible = false;
    },
    // 搜索事件
    search() {
      if (!(this.formInline.warehousename == "")) {
        this.$axios
          .get(
            "/api/warehouse/findByName/" +
              this.pageparm.currentPage +
              "/" +
              this.pageparm.pageSize +
              "/" +
              encodeURI(encodeURI(this.formInline.warehousename))
          )
          .then(res => {
            console.log(res);
            if (res.data.code == 200) {
              this.listData = res.data.data.list;
              this.pageparm.total = res.data.data.total;
            }
          })
          .catch();
      }
    },
    reset() {
      this.getdata(this.formInline);
      this.formInline.warehousename
    },
    //选中的数据的数组
    handleSelectionChange(val) {
      this.batchDeleteArr = [];
      for (let index in val) {
        this.batchDeleteArr[index] = val[index].id;
      }
    },
    //获取仓库分类下拉框数据
    getWarehosueData() {
      this.$axios
        .get("/api/warehousetype/findAll")
        .then(res => {
          console.log(res + "111");
          this.warehouseData = res.data.data;
        })
        .catch();
    },
    //批量删除数据
    deleteSome() {
      this.$confirm("确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .put("/api/warehouse/deleteSome", this.batchDeleteArr)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  message: "批量删除成功",
                  type: "success"
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message
                });
              }
            })
            .catch(err => {
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //显示编辑界面
    //新增页面
    addOne() {
      this.getWarehosueData();
      this.editFormVisible = true;
      this.title = "添加";
      this.editForm.id = "";
      this.editForm.warehousename = "";
      this.editForm.warehouse_id = "";
      this.editForm.warehouse_classify = "";
      this.editForm.warehouse_style = "";
      this.editForm.warehouse_remark = "";
    },
    //修改页面
    update(row) {
      this.getWarehosueData();
      this.editFormVisible = true;
      this.title = "修改";
      this.editForm.id = row.id;
      this.editForm.warehousename = row.warehousename;
      this.editForm.warehouse_id = row.warehouse_id;
      this.editForm.warehouse_classify = row.warehouse_classify;
      this.editForm.warehouse_style = row.warehouse_style;
      this.editForm.warehouse_remark = row.warehouse_remark;
    },
    // 编辑、增加页面保存方法
    save() {
      this.$refs["editForm"].validate(valid => {
        if (!valid) {
          this.$message.error("请按要求填写表单！");
        } else {
          //判断是增加还是修改
          if (this.editForm.id == "") {
            //新增
            this.$axios
              .post("/api/warehouse/addOne", this.editForm)
              .then(res => {
                console.log(res);
                if (res.data.code == 200) {
                  this.$message({
                    message: "添加成功",
                    type: "success"
                  });
                  //成功后关掉弹出框
                  this.$refs["editForm"].resetFields();
                  this.editFormVisible = false;
                  //同时刷新数据
                  this.getdata(this.formInline);
                } else {
                  this.$message({
                    type: "info",
                    message: res.data.message
                  });
                }
              })
              .catch(err => {
                this.editFormVisible = false;
                this.$message.error("保存失败，请稍后再试!");
              });
          } else {
            this.$axios
              .put("/api/warehouse/update", this.editForm)
              .then(res => {
                console.log(res);
                if (res.data.code == 200) {
                  this.$message({
                    message: "修改成功",
                    type: "success"
                  });
                  //成功后关掉弹出框
                  this.$refs["editForm"].resetFields();
                  this.editFormVisible = false;
                  //同时刷新数据
                  this.getdata(this.formInline);
                } else {
                  this.$message({
                    message: res.data.message,
                    type: "info"
                  });
                }
              })
              .catch(err => {
                this.editFormVisible = false;
                this.$message.error("修改失败，请稍后再试!");
              });
          }
        }
      });
    },
    // 删除数据
    deleteOne(row) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .put("/api/warehouse/delete/" + row.warehouse_id)
            .then(res => {
              console.log(res);
              if (res.data.code == 200) {
                this.$message({
                  message: "删除成功",
                  type: "success"
                });
                //同时刷新数据
                this.getdata(this.formInline);
              } else {
                this.$message({
                  message: res.data.message,
                  type: "info"
                });
              }
            })
            .catch(error => {
              thid.message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            message: "已取消删除",
            type: "info"
          });
        });
    },
    //新增弹窗里点击仓库分类拿到另一张表的数据
    addStyle() {
      this.LogDialogVisible = true;
    },
    // watch: {
    //   $route(to, from) {
    //     console.log(to);
    //     console.log(from);
    //   }
    // },
    // 上传前判断文件格式
    beforeUpload(file) {
      console.log(file.type);
      const type =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!type) {
        this.$message.error("请上传EXCEL格式的文件!");
      }
      return type;
    },
    //上传成功回调方法
    handlesuccess(res) {
      if (res.code == 200) {
        //刷新数据
        this.getdata();
        this.$message({
          type: "success",
          message: "操作成功！"
        });
      } else {
        this.$message({
          type: "info",
          message: res.message
        });
      }
    },
    //导出数据
    exportData() {
      this.$axios
        .get("/api/warehouse/export", {
          responseType: "blob"
        })
        .then(response => {
          //通过header中获取返回的文件名称
          let fileName = response.headers["content-disposition"]
            .split(";")[1]
            .split("filename=")[1];
          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel"
          });
          let downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          //指定下载的文件的名称，切记进行decode
          downloadElement.download = decodeURI(fileName);
          document.body.appendChild(downloadElement);
          downloadElement.click();
          //移除临时创建对象，释放资源
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        });
    },
    // 关闭编辑、增加弹出框
    cancelDialog() {
      this.$refs["editForm"].resetFields();
      this.editFormVisible = false;
    },
    closeDialog(done) {
      this.$refs["editForm"].resetFields();
      done();
    }
  }
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>
